<script setup lang="ts">
import { ref, onBeforeUnmount, reactive, onMounted, watchEffect, watch } from 'vue'
import { useUserStore } from '../../store/modules/user'
import { sessionStorage } from '../../utils/storage';
import { download_file2, GetuserInfo } from '../../utils/ipcRequest';
import { useRouter } from "vue-router";
// import { setCookie } from '../../utils/auth'
import { userSiteList } from "../../api/home"
import { Empty } from 'ant-design-vue';
import ContextMenu from '../../components/ContextMenu.vue';
import publishArticle from '../../components/publishArticle.vue'
import { userSiteArticleZipImage, userSiteArticleList, articleLists, articleRemove,articleWithdraw, pictureUploadproxy, adnewspvtrend, getAppStatistic,getauthorhistory, getNewtotalincome, articlePublishNum, getSquareMissionList } from '../../api/article'
type Key = string | number;
const userStore = useUserStore()
const router = useRouter();
// 去详情页列表
const onDetails = (site_id:any, cookie:any) => {
  console.log('跳转页面了')
  // router.push({path: '/articleList', query: {siteId:16 site_id, cookie: 'BIDUPSID=9783AE509A6A036AAC8B53CCEB41763C; PSTM=1705024699; BDUSS=4weTUteTJSTXhrNUVuc05OZjRXSzk2RzJLNURmS3V1b1BEQWNTQ09CdWlQbkJtSUFBQUFBJCQAAAAAAAAAAAEAAADXtQO4va3j69bTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKKxSGaisUhmVn; BDUSS_BFESS=4weTUteTJSTXhrNUVuc05OZjRXSzk2RzJLNURmS3V1b1BEQWNTQ09CdWlQbkJtSUFBQUFBJCQAAAAAAAAAAAEAAADXtQO4va3j69bTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKKxSGaisUhmVn; MAWEBCUID=web_cZszphDSxGIzOqcQhAhfKyaToGOCRAUixLRqECRcQSKibcurXH; BAIDUID=8A2C4E89670246269AB9ACB328B14E8C:FG=1; PHPSESSID=gk1tka5e4pefu58oj0tettr6q3; H_WISE_SIDS_BFESS=110085_633616_633567_638431_638466_638129_638943_638941_638947_638939_639209_638578_639384_639805; H_WISE_SIDS=60278_61027_61737_61780_61890_61986; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=60278_61027_61737_61780_61890_61953_61956_61986; BAIDUID_BFESS=8A2C4E89670246269AB9ACB328B14E8C:FG=1; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; delPer=0; PSINO=2; Hm_lvt_f7b8c775c6c8b6a716a75df506fb72df=1737603066; HMACCOUNT=D50073EF615640A1; __bid_n=1949136ab9495527b2482f; theme=bjh; devStoken=5a8a3cba629a77175c43c7bc704881334fae7ad172b3d51a58ec9c4ddc61e8f2; bjhStoken=410de1773f74b11bd1ec8646165336204fae7ad172b3d51a58ec9c4ddc61e8f2; XFT=0dxdQcZBbBMte+zMHVUcERthzYUDB7Yc1Buaky4h2jE=; RT="z=1&dm=baidu.com&si=e253fc38-c504-414e-ac0d-5afeff908ea5&ss=m68s023n&sl=1&tt=42u&bcn=https%3A%2F%2Ffclog.baidu.com%2Flog%2Fweirwood%3Ftype%3Dperf"; Hm_lpvt_f7b8c775c6c8b6a716a75df506fb72df=1737603096; XFI=8d2caaa0-d93a-11ef-b6f7-0744177964f3; XFCS=7C1D9EF7DBDC64918DC224671E56F6FFD222CF7BCD4216861B9BFBB3997E1A6A; ab_sr=1.0.1_NjMyMDgzMmQ1YzMxZmQ5YzQzNzkzYTM0MGEyNTYwZTUxYzBkZWM3ODZiNTgzY2MyNjQwMzlhNTNiYjA0MGJlZjRiMDYxMmI5MTcwZDdiZDI4ZjRjNjVjMGUzZmUzY2ViZWI1OWZjZWJkYmFmN2MyM2UyYTAzMDQxYmQ0ZmY2OTZlMGQ5MDY0ODViMTMwOGQ4ZmJhZmM0MDdiNGIxZDk3YmZmZWVmOTM2Y2IwMDY0MTI0ZjA3YTZlMTQxNWZjNWM5MDY5MWZhNjRmZGQ3NzE5ZjU1NTc1Y2FkZTk4NWYzYzdjY2Q4MzkwNGE1ZDY5ZjUyYmFlMWNkOWRlNTljZTQ0Yg=='}})
  if(isSeeDetails.value) {
    router.push({path: '/articleList', query: {siteId: site_id, cookie: cookie ? cookie : ''}})
  } else {
    // message.warning('正在下载中');
  }
}

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
const current = ref<number>(1); // 页数
const pageSize = ref<number>(15)
const total = ref<number>(0); // 总数
const siteList:any = ref([])
const formState = reactive({
  checked1: false
});
const formStateRef = ref();
const labelCol = { span: 14 };
const wrapperCol = { span: 10 };
const onChange = (pageNumber: number) => {
  current.value = pageNumber
  isStop.value = true
  onUserSiteList()
};

const onChangeMonitor = (e) => {
  console.log(e)
  formState.checked1 = e
  userStore.changeMonitor(e)

  if(formState.checked1 == true && siteList.value.length > 0) {
      isStop.value = false
      onArticleList(0)
      // onDeleteRefresh(0)
  } else {
    isStop.value = true
    if (timer.value) {
      clearTimeout(timer.value)
      timer.value = null
    }
    if (timer2.value) {
      clearTimeout(timer2.value)
      timer2.value = null
    }
    if (timer3.value) {
      clearTimeout(timer3.value)
      timer3.value = null
    }
  }
}
// 获取站点信息
const initLoading = ref(false)
const state = reactive<{
  selectedRowKeys: Key[];
  selectedRows: Key[];
  loading: boolean;
  indeterminate: boolean,
  checkAll: boolean,
  refreshLoading:boolean,
  inspectionLoading: boolean
}>({
  selectedRowKeys: [], // Check here to configure the default column
  selectedRows: [],
  loading: false,
  indeterminate: false,
  checkAll: false,
  refreshLoading:false, // 数据刷新加载
  inspectionLoading: false, // 每日巡检
});
const onUserSiteList = () => {
  initLoading.value = true
  userSiteList({page: current.value}).then((response:any) => {
    const result = response.data
    result.data.data.forEach((item:any) => {
      item.isVisible = false
    })
    if(sessionStorage.get(`site_list_num`)) {
      let site_num = JSON.parse(sessionStorage.get(`site_list_num`))
        // 将 array2 中的 description 赋值到 array1 中
      siteList.value = result.data.data.map(item1 => {
        const item2 = site_num.find(item2 => item2.site_id === item1.site_id);
        if (item2) {
          return { ...item1,isVisible:false, read_amount: item2.read_amount,yesterday_view_count:item2.yesterday_view_count,total_view_count:item2.total_view_count,income:item2.income, publish_num_left: item2.publish_num_left, publish_num_text: item2.publish_num_text, today_publish_num:item2.today_publish_num, pulish_num: item2.pulish_num,activity_list: item2.activity_list, square_mission_List: item2.square_mission_List};
        }
        return item1;
      });
      total.value = result.data.total
      initLoading.value = false
      let monitor = userStore.monitor
      formState.checked1 = monitor
      if(monitor == true && siteList.value.length > 0) {
        isStop.value = false
        onArticleList(idxs.value)
      } else {
        if (timer.value) {
          clearTimeout(timer.value)
          timer.value = null
        }
        if (timer2.value) {
          clearTimeout(timer2.value)
          timer2.value = null
        }
        if (timer3.value) {
          clearTimeout(timer3.value)
          timer3.value = null
        }
      }
    } else {
      siteList.value = result.data.data
      total.value = result.data.total
      otherGetData(0)
    }
  })
  .catch(err => { console.log('err',err);initLoading.value = false})
}

// 获取文章列表
const timer:any = ref(null)
const timer2:any = ref(null)
const articleList:any = ref([])
const isStop = ref(false) // 是否停止
const inProgressData:any = ref({})
const isSeeDetails = ref(false) // 判断是否可以点进列表
const onArticleList = (idx:any) => {
  const executeNext = (index) => {
      if(index >= siteList.value.length) {
        clearTimeout(timer.value)
        clearTimeout(timer2.value)
        timer2.value = null
        timer.value = null
        isSeeDetails.value = true
        timer.value = setTimeout(() => {
          arrIdx.value = []
          onArticleList(0)
        }, 4000)
        return
      }
      siteList.value[idx].download_status = false
      siteList.value[idx].download_status_reason = ''
      siteList.value[idx].progressBar = ''
      siteList.value[idx].errorColor2 = ''
      siteList.value[idx].upload_status = false
      siteList.value[idx].upload_status_reason = ''
      siteList.value[idx].upload_text = ''
      siteList.value[idx].errorColor1 = ''
      siteList.value[idx].imgNum = ''
      siteList.value[idx].list_status = false
      siteList.value[idx].list_status_text = ''
      siteList.value[idx].list_status_reason = ''
      siteList.value[idx].errorColor = ''
      const currentItem = siteList.value[index];
      userSiteArticleList({page: 1,limit: 15, siteId: currentItem.site_id}).then((response:any) => {
        const result = response.data.data
        result.data.forEach((item:any) => {
          item.isDownload = false
        })
        // articleList.value = result.data
        // if(!isStop.value) {
        //   onGetuserinfo(currentItem.port_config.cookie, currentItem.site_id, idx) // 从返回的header中解析出token
        // }
        if(siteList.value.length> 0) {
          inProgressData.value = siteList.value[idx]
        }
        processItems(result.data, idx)
      }).catch(() => {
        timer.value = setTimeout(() => {
          executeNext(index + 1)
        }, 2000)
      })
    }
    executeNext(idx)
}

// 默认获取是否有下载
const processItems = async (data:any, idx:any) => {
      for (let i in data) {
        let path = `images_${data[i].article_id}`; // 从开始到点号位置截取字符串
        const result = await window.electron.ipcRenderer.invoke('list-directory', path); // 等待操作完成
        // console.log(result)
        // 处理结果或更新数组项
        if(Array.isArray(result.imageArr)) {
          if(result.imageArr.length != 0) {
            data[i]['isDownload'] = true
            data[i]['downloadReason'] = '已解压' // 将修改后的对象添加到新数组中
          } else {
            data[i]['isDownload'] = false
            data[i]['downloadReason'] = ''
          }
        } else {
          data[i]['isDownload'] = false
          data[i]['downloadReason'] = ''
        }

        // 获取图片文件
        let pathJson = `images_${data[i].article_id}.json`;
        const resFile = await window.electron.ipcRenderer.invoke('json-directory', pathJson); // 等待操作完成
        // console.log(resFile,'resFile')
        if(resFile.type == 2) {
          let jsonData = JSON.parse(resFile.urlArr)
          data[i]['isUpload'] = true
          data[i]['uploadReason'] = '已上传' // 将修改后的对象添加到新数组中
          data[i]['uploadText'] = '已上传'
          data[i]['imgNum'] = jsonData.data.length
        } else if(resFile.type == 1 && data[i]['is_release'] == 0 && data[i]['status'] == 50 && data[i]['img_status'] == 20 && data[i]['isDownload']) {
          data[i]['isUpload'] = false
          data[i]['uploadReason'] = '' // 将修改后的对象添加到新数组中
          data[i]['uploadText'] = ''
        } else {
          data[i]['isUpload'] = false
          data[i]['uploadReason'] = '' // 将修改后的对象添加到新数组中
          data[i]['uploadText'] = ''
        }
      }
      articleList.value = data
      onArticleZipImage(idx)
};
function getFilenameFromURL(url) {
    // 找到最后一个 '/' 的位置
    const lastIndex = url.lastIndexOf('/');
    // 使用 substring 从最后一个 '/' 位置之后开始截取，直到字符串末尾
    const filename = url.substring(lastIndex + 1);
    // 返回文件名，但不包括后缀名
    // return filename.split('.').slice(0, -1).join('.');
    return filename;
}

// 获取压缩文件
const arrIdx:any = ref([]) // 用来存储遍历的id,不同去获取，相同账号直接跳过获取token
const flag = ref(0)
const idxs:any = ref(0)
const onArticleZipImage = async (idx:any) => {
  let articleLists = articleList.value.filter((item1:any) => item1.is_release == 0 && item1.status == 50 && item1.img_status == 20 && !item1.isDownload)
  // if(!isStop.value) {
  console.log(articleLists,'articleLists')
  articleLists = articleLists.filter((_, index:any) =>index < 5)
  const executeNexts = (index) => {
    if(index >= articleLists.length) {
      console.log(siteList.value[idx].list_status,flag.value,'执行顺序')
      // if(siteList.value[idx].list_status == true) {
        // if(!isStop.value) {
        //   timer2.value = setTimeout(() => {
        //       arrIdx.value = []
        //       onArticleList(idx + 1)
        //   }, 4000)
        // }
      // } else {
        timer2.value = setTimeout(() => {
          onDeleteRefresh(idx)
        }, 2000)
      // }
      // if(articleList.value.length> 0) {
        siteList.value[idx].download_status = true
        siteList.value[idx].download_status_reason = `已解压`
      // }
      return
    }
    const currentItem = articleLists[index];
    if(currentItem['cover'] || currentItem['vertical_cover']) {
      userSiteArticleZipImage({articleId: currentItem['article_id']}).then(async(response:any) => {
          const result = response.data
          let urlValue = {
            url: result.url,
            fileName: getFilenameFromURL(result.url),
            article_id: currentItem['article_id']
          }
          console.log(result,urlValue,'result')
          siteList.value[idx].download_status = false
          siteList.value[idx].download_status_reason = `正在解压`
          siteList.value[idx].errorColor2 = ''
          siteList.value[idx].progressBar = ''
          siteList.value[idx].upload_status = false
          siteList.value[idx].upload_status_reason = ''
          siteList.value[idx].upload_text = ''
          siteList.value[idx].errorColor1 = ''
          siteList.value[idx].imgNum = ''
          siteList.value[idx].list_status = false
          siteList.value[idx].list_status_text = ''
          siteList.value[idx].list_status_reason = ''
          siteList.value[idx].errorColor = ''
          imgNum.value = 0
          idxs.value = idx
          isSeeDetails.value = false
          // 监听主进程的回复
         let downloadObj:any = await download_file2(result.url,currentItem['article_id'])
         console.log('下载返回的数据',downloadObj)
         let downloadResult = JSON.parse(downloadObj)
         if(downloadResult.success) {
            isDownloadResume.value = true
            if(downloadResult.status == 2 || downloadResult.status == 1) {
              currentItem.isDownload = true
              currentItem.downloadReason = '已解压'
              siteList.value[idx].download_status = true
              siteList.value[idx].download_status_reason = `已解压`
              timer2.value = setTimeout(() => {
                onDeleteRefresh(idx)
              }, 2000)
            }else if(downloadResult.status == 3 || downloadResult.status == 4) {
              currentItem.isDownload = false
              currentItem.downloadReason = downloadResult.message
              siteList.value[idx].download_status = false
              siteList.value[idx].download_status_reason = downloadResult.message
              timer2.value =  setTimeout(() => {
                executeNexts(index)
              }, 3000)
            } else{
              timer2.value = setTimeout(() => {
                executeNexts(index + 1)
              }, 2000)
              currentItem.isDownload = false
              currentItem.downloadReason = '解压失败'
              let pathJson = `images_${currentItem['article_id']}.zip`;
              siteList.value[idx].download_status = false
              siteList.value[idx].download_status_reason = `解压失败`
              window.electron.ipcRenderer.invoke('delete-file', pathJson).then(res => {
                if(res.success) {
                  console.log('文件删除成功')
                } else {
                  console.log('删除文件失败',res.message)
                }
              })
            }
         } else {
            currentItem.isDownload = false
            currentItem.downloadReason = '解压失败'
            siteList.value[idx].download_status = false
            siteList.value[idx].download_status_reason = `解压失败`
            siteList.value[idx].errorColor2 = 'error'
            timer2.value = setTimeout(() => {
              executeNexts(index + 1)
            }, 2000)
         }
          // window.electron.ipcRenderer.invoke('download-file-request2', `https://www.huaicaikeyu.cn`+result.url).then((res) => {
          //   console.log(res)
          //   let result = JSON.parse(res)
          //   isDownloadResume.value = true
          //   if(result.status == 2 || result.status == 1) {
          //     currentItem.isDownload = true
          //     currentItem.downloadReason = '已解压'
          //     // timer2.value = setTimeout(() => {
          //     //   executeNexts(index + 1)
          //     // }, 2000)
          //     siteList.value[idx].download_status = true
          //     siteList.value[idx].download_status_reason = `已解压`
          //     timer2.value = setTimeout(() => {
          //       onDeleteRefresh(idx)
          //     }, 2000)
          //   }else if(result.status == 3 || result.status == 4) {
          //     currentItem.isDownload = false
          //     currentItem.downloadReason = result.message
          //     siteList.value[idx].download_status = false
          //     siteList.value[idx].download_status_reason = result.message
          //     timer2.value =  setTimeout(() => {
          //       executeNexts(index)
          //     }, 3000)
          //   } else{
          //     timer2.value = setTimeout(() => {
          //       executeNexts(index + 1)
          //     }, 2000)
          //     currentItem.isDownload = false
          //     currentItem.downloadReason = '解压失败'
          //     let pathJson = `images_${currentItem['article_id']}.zip`;
          //     siteList.value[idx].download_status = false
          //     siteList.value[idx].download_status_reason = `解压失败`
          //     window.electron.ipcRenderer.invoke('delete-file', pathJson).then(res => {
          //       if(res.success) {
          //         console.log('文件删除成功')
          //       } else {
          //         console.log('删除文件失败',res.message)
          //       }
          //     })
          //   }
          // }).catch((error) => {
          //   console.log(error); // 输出下载错误信息
          //   currentItem.isDownload = false
          //   currentItem.downloadReason = '解压失败'
          //   siteList.value[idx].download_status = false
          //   siteList.value[idx].download_status_reason = `解压失败`
          //   siteList.value[idx].errorColor2 = 'error'
          //   timer2.value = setTimeout(() => {
          //     executeNexts(index + 1)
          //   }, 2000)
          // });
      }).catch(() => {
        currentItem.isDownload = false
        currentItem.downloadReason = '下载失败'
        siteList.value[idx].download_status = false
        siteList.value[idx].download_status_reason = `解压失败`
        siteList.value[idx].errorColor2 = 'error'
        timer2.value = setTimeout(() => {
            executeNexts(index + 1)
          }, 2000)
      })
    } else {
      currentItem.isDownload = false
      currentItem.downloadReason = '无解压文件'
      siteList.value[idx].download_status = false
      siteList.value[idx].download_status_reason = `解压失败`
      siteList.value[idx].errorColor2 = 'error'
      timer2.value = setTimeout(() => {
        executeNexts(index + 1)
      }, 2000)
    }
  }
  executeNexts(0)
  // }
}
const listUploadFun = (idx:any,uploadIdx:any) => {
  let articleList2 = articleList.value.filter((item1:any) =>item1.is_release == 0 && item1.status == 50 && item1.img_status == 20 && item1.isDownload && !item1.isUpload)
  // let articleList3 = articleList.value.filter((item1:any) =>item1.is_release == 1 || item1.isDownload)
  articleList.value.forEach(item1 => {
    if (item1.is_release == 0 && item1.status == 50 && item1.img_status == 20  && item1.isDownload && !item1.isUpload) {
      item1.isUpload = false
      item1.uploadText = ''
      item1.uploadReason = ''
    }
  });
  console.log(articleList2, 'articleList2')
  articleList2 = articleList2.filter((_, index:any) =>index < 5)
  if(!isStop.value) {
    const executeNexts = async (index) => {
      if (index >= articleList2.length) {
        if (!isStop.value) {
          siteList.value[idx].upload_status = true
          siteList.value[idx].upload_status_reason = '已上传'
          siteList.value[idx].upload_text = '已上传'
          let list = articleList.value.filter((item1:any) =>item1.is_release == 0 && item1.status == 50 && item1.img_status == 20 && item1.isDownload && item1.isUpload)
          siteList.value[idx].pulish_num = list.length
          onListDel(idx)
        }
        return
      }
      const currentItem = articleList2[index];
      const resArr = await window.electron.ipcRenderer.invoke('read-file', `images_${currentItem.article_id}`)
      console.log(resArr); // 输出下载成功信息
      if (Array.isArray(resArr)) {
        currentItem.isUpload = false
        currentItem.uploadReason = '正在上传'
        currentItem.uploadText = '正在上传'
        siteList.value[idx].upload_status = false
        siteList.value[idx].upload_status_reason = '正在上传'
        siteList.value[idx].upload_text = '正在上传'
        siteList.value[idx].errorColor1 = ''
        siteList.value[idx].imgNum = ''
        imgNum.value = 0
        uploadPhotos(resArr, currentItem.article_id, idx) // 上传图片
      }
    }
    executeNexts(uploadIdx)
  }
}
const imgNum = ref(0)
// 上传图片
const uploadPhotos = async (val:any, article_id:any, idx:any) => {
  // 同步请求
  var array:any = []
  const executeNexts = async (index) => {
    // 判断循环执行完了后执行
    if(index >= val.length) {
      let pathJson = `images_${article_id}.json`;
      let datas = { data: array}
      console.log(datas)
      const result = await window.electron.ipcRenderer.invoke('create-file', pathJson, datas);
      console.log(result,'文件创建成功!')
      if (result.success) {
        articleList.value.forEach(item1 => {
          if (article_id == item1.article_id && item1.is_release == 0) {
            item1.isUpload = true
            item1.uploadReason = '已上传'
            item1.uploadText = '已上传'
            item1.imgNum = imgNum.value
          }
        });
        siteList.value[idx].upload_status = true
        siteList.value[idx].upload_status_reason = '已上传'
        siteList.value[idx].upload_text = '已上传'
        siteList.value[idx].imgNum = imgNum.value
        setTimeout(() => {
          listUploadFun(idx, 0)
        }, 2000)
      } else {
        articleList.value.forEach(item1 => {
          if (article_id == item1.article_id && item1.is_release == 0) {
            item1.isUpload = false
            item1.upload_text = '上传失败'
            item1.uploadReason = '文件创建失败'
          }
        });
        siteList.value[idx].upload_status = false
        siteList.value[idx].upload_status_reason = '文件创建失败'
        siteList.value[idx].upload_text = '上传失败'
        siteList.value[idx].errorColor1 = 'error'
        console.log(`创建文件失败：${result.message}`);
        if (!isStop.value) {
          onListDel(idx)
        }
      }
      console.log('sdsssdfsdf', array)
      return
    }
    if(!isStop.value) {
      const currentItem = val[index];
      const blob = new Blob([currentItem.data],{type: "application/octet-stream"}); //, { type: `${item.type}`} 根据文件类型调整 MIME 类型
      // let file:any =  new File([currentItem.data],currentItem.name,{type:currentItem.type})
      const FormDatas = new FormData();
      FormDatas.append("type", 'image');
      FormDatas.append("app_id", '1788758126357619');
      FormDatas.append("is_waterlog", '0');
      FormDatas.append("save_material", '1');
      FormDatas.append("is_events", '');
      FormDatas.append("article_type", 'news');
      FormDatas.append("media", blob, currentItem.name);
      // array = new Promise((resolve, reject) => {
      //api.upload_uploadImages后端给的图片上传解析的接口方法
      pictureUploadproxy(FormDatas).then((response:any) => {
        const result = response.data.ret
        let width:any = ''
        let height:any = ''
        const img = new Image();
        img.src = result.https_url;
        img.onload = () => {
          // 图片加载完成后，获取宽高
          // console.log('Width:', img.width, 'Height:', img.height);
          // 可以在这里做一些处理，比如验证图片尺寸等
          width = img.width
          height = img.height
        };
        let articleId = { article_id: article_id, width: width, height: height }
        imgNum.value = index + 1
        siteList.value[idx].imgNum = index + 1
        let urlValue = {
          status: 'fulfilled',
          value:{...result, ...articleId }
        }
        array.push(urlValue)
        setTimeout(() => {
          executeNexts(index + 1)
        }, 1000)
        // resolve(urlValue)
      }).catch((err) => {
        // reject(err)
        articleList.value.forEach(item1 => {
          if (article_id == item1.article_id && item1.is_release == 0) {
            item1.isUpload = false
            item1.uploadReason = err.message
            item1.upload_text = '上传失败'
          }
        });
        siteList.value[idx].upload_status = false
        siteList.value[idx].upload_status_reason = err.message
        siteList.value[idx].upload_text = '上传失败'
        siteList.value[idx].errorColor1 = 'error'
        siteList.value[idx].imgNum = ''
        // console.log(err.message)
        if (!isStop.value) {
          onListDel(idx)
        }
      })
    }
  }
  executeNexts(0)
}
// 一键发布
const onPulish = (data: any) => {
    console.log('45345345435',data)
    isStop.value = data.isUpload 
}
// 清除选中的数据
const onClear = () => {
  state.selectedRows = []
  state.selectedRowKeys = []
}
// 刷新列表
const onRefreshList = () => {
  isStop.value = true
  onUserSiteList() // 站点列表
}

// 删除列表
const timer3:any = ref(null)
const onDeleteRefresh = (idx:any) => {
  clearTimeout(timer3.value)
  timer3.value = null
  if(!isStop.value) {
    console.log(arrIdx.value)
    if(arrIdx.value.length == 0 || (arrIdx.value.length > 0 && arrIdx.value[0] != idx)) {
      arrIdx.value.push(idx)
      const executeNextDel = (index) => {
        if(index >= siteList.value.length) {
          console.log('sdsdsdsdsddsd',siteList.value.length)
          // if(siteList.value.length != 0) {
          //   onDeleteRefresh(0)
          // }
          return
        }
        const currentItem = siteList.value[index];
        if(currentItem.port_config.cookie) {
          if(!isStop.value) {
            onGetuserinfo(currentItem.port_config.cookie,currentItem.site_id , idx) // 从返回的header中解析出token
          }
        }
      }
      executeNextDel(idx)
      console.log('不同账户获取token')
    } else {
      console.log('相同账号直接跳过获取token')
      // onListDel(idx)
      listUploadFun(idx,0)
    }
  }
}

// 从返回的header中解析出token
const onGetuserinfo = async (cookie,site_id:any, idx:any) => {
    let userInfoObj:any = await GetuserInfo(cookie,site_id)
    console.log('设置返回：',userInfoObj)
    let userInfoResult = JSON.parse(userInfoObj)
    if(userInfoResult.success) {
      listUploadFun(idx,0)
    } else {
      if (!isStop.value) {
        onListDel(idx)
      }
    }
}
// 文章列表-定时监测数据
const onListDel = (idx:any) => {
  let obj = {
        currentPage: 1,
        pageSize: 10,
        search: '',
        type: 'news',
        collection: '',
        clearBeforeFetch: false
    }
    console.log('监测列表')
    if(!isStop.value) {
      siteList.value[idx].list_status = false
      siteList.value[idx].list_status_text = '正在监测'
      siteList.value[idx].list_status_reason = '正在监测'
      articleLists(obj).then((response:any) => {
        const result = response.data.data
        let arr = result.list.filter((item2:any) => item2['status'] == 'rejected' || (item2['status'] == 'publish' && item2.audit_msg != '') || (item2['status'] == 'forbidden' && item2.audit_msg != ''))
        // 自动删除审核未通过的文章
        if(arr.length > 0) {
            const executeNext2 = (index) => {
              if(index >= arr.length) {
                siteList.value[idx].list_status = true
                siteList.value[idx].list_status_text = '已完成'
                siteList.value[idx].list_status_reason = '已完成'
                console.log(idx)
                if(!isStop.value) {
                  timer2.value = setTimeout(() => {
                      arrIdx.value = []
                      onArticleList(idx + 1)
                  }, 4000)
                }
                return
              }
              if(arr[index]['status'] == 'publish') {
                if(!isStop.value) {
                  // 状态已发布-先撤回再删除
                  articleWithdraw({article_id: arr[index]['article_id']}).then((response:any) => {
                      const result = response.data
                      console.log('articleRemove',result)
                      articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                          console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                          timer3.value =  setTimeout(() => {
                            executeNext2(index+1)
                          }, 2000)
                      }).catch((err) => {
                        timer3.value =  setTimeout(() => {
                          executeNext2(index+1)
                        }, 2000)
                        siteList.value[idx].list_status = false
                        siteList.value[idx].list_status_reason = err.message
                        siteList.value[idx].list_status_text = '监测失败'
                        siteList.value[idx].errorColor = 'error'
                      });
                  }).catch((err) => {
                    timer3.value =  setTimeout(() => {
                      executeNext2(index+1)
                    }, 2000)
                    siteList.value[idx].list_status = false
                    siteList.value[idx].list_status_reason = err.message
                    siteList.value[idx].list_status_text = '监测失败'
                    siteList.value[idx].errorColor = 'error'
                  });
                }
              } else {
                if(!isStop.value) {
                  articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                      console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                      timer3.value = setTimeout(() => {
                        executeNext2(index+1)
                      }, 2000)
                  }).catch((err) => {
                    flag.value++
                    timer3.value = setTimeout(() => {
                      executeNext2(index+1)
                    }, 3000)
                    siteList.value[idx].list_status = false
                    siteList.value[idx].list_status_reason = err.message
                    siteList.value[idx].list_status_text = '监测失败'
                    siteList.value[idx].errorColor = 'error'
                  });
                }
              }
            }
            executeNext2(0)
        } else {
          if(!isStop.value) {
            timer2.value = setTimeout(() => {
                arrIdx.value = []
                onArticleList(idx + 1)
            }, 4000)
          }
          siteList.value[idx].list_status = true
          siteList.value[idx].list_status_text = '已完成'
          siteList.value[idx].list_status_reason = '已完成'
        }
      }).catch((err) => {
        siteList.value[idx].list_status = false
        siteList.value[idx].list_status_reason = err.message
        siteList.value[idx].list_status_text = '监测失败'
        siteList.value[idx].errorColor = 'error'
        if(!isStop.value) {
          timer2.value = setTimeout(() => {
              arrIdx.value = []
              onArticleList(idx + 1)
          }, 4000)
        }
      })
    }
}

// 数据刷新
const onDataRefresh = () => {
  isStop.value = true
  state.refreshLoading = true
  otherGetData(0)
}

const read_site_amount:any = ref([]) // 获取存储的站点数据
// 获取每个账号的数据
const otherGetData = (idx:any) => {
  const executeNext_2 = async (index) => {
    if(index >= siteList.value.length) {
      // siteList.value[idx].list_status = true
      // siteList.value[idx].list_status_reason = '已完成'
      initLoading.value = false
      state.refreshLoading = false
      let monitor = userStore.monitor
      console.log('5445monitor',monitor,siteList.value)
      formState.checked1 = monitor
      for(let i in siteList.value) {    
        let Data = { 
          read_amount: siteList.value[i].read_amount,
          yesterday_view_count: siteList.value[i].yesterday_view_count,
          total_view_count: siteList.value[i].total_view_count,
          income: siteList.value[i].income,
          publish_num_left: siteList.value[i].publish_num_left, // 剩余发布
          publish_num_text: siteList.value[i].publish_num_text, // 剩余发布文字信息
          today_publish_num: siteList.value[i].today_publish_num, // 今日发布
          pulish_num: siteList.value[i].pulish_num, // 文章可发布数
          activity_list: siteList.value[i].activity_list, // 设置列表
          square_mission_List: siteList.value[i].square_mission_List, // 征文任务列表
          site_id: siteList.value[i].site_id
        }
        read_site_amount.value.push(Data)
      }
      sessionStorage.set(`site_list_num`,JSON.stringify(read_site_amount.value))
      if(monitor == true && siteList.value.length > 0) {
        isStop.value = false
        onArticleList(0)
      } else {
        if (timer.value) {
          clearTimeout(timer.value)
          timer.value = null
        }
        if (timer2.value) {
          clearTimeout(timer2.value)
          timer2.value = null
        }
        if (timer3.value) {
          clearTimeout(timer3.value)
          timer3.value = null
        }
      }
      return
    }
    const currentItem = siteList.value[index]
    if(currentItem.port_config && currentItem.port_config.cookie) {
      let userInfoObj:any = await GetuserInfo(currentItem.port_config.cookie,currentItem.site_id)
      console.log('设置返回：',userInfoObj)
      let userInfoResult = JSON.parse(userInfoObj)
      if(userInfoResult.success) {
        onAdnewspvtrend(index)
      } else {
        executeNext_2(index + 1)
      }
    }
  }
  executeNext_2(idx)
}
//百家号获取阅读量
const onAdnewspvtrend = (index:any) => {
 // 获取当前日期和时间
 const now = new Date();
  // 获取当天零点的时间戳（毫秒）
  const todayMidnight = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
  // 昨天零点的时间戳（秒）
  const yesterdayMidnight:any = (todayMidnight - 24 * 60 * 60 * 1000) / 1000; // 减去一天的时间（秒）
  // 前天零点的时间戳（秒）
  const dayBeforeYesterdayMidnight = yesterdayMidnight - 24 * 60 * 60 ; // 再减去一天的时间（秒）
  let obj = {
    type: 'ad_income',
    start_date: dayBeforeYesterdayMidnight,
    end_date: yesterdayMidnight,
    // start_date: 1740153600,
    // end_date: 1740240000,
    version: 3
  }
  adnewspvtrend(obj).then((response:any) => {
      const result = response.data.data
      siteList.value[index].read_amount = result
      onAppStatistic(index)
  }).catch(() => {
      onAppStatistic(index)
  })
}
//获取昨日日期
const yesterdayDate = () => {
  const today:any = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1); // 将日期设置为昨天
  const year = yesterday.getFullYear();
  const month = String(yesterday.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，需要+1，并且确保是两位数
  const day = String(yesterday.getDate()).padStart(2, '0'); // 获取日期并确保是两位数
  return `${year}${month}${day}`;
}
// 百家号获取昨日阅读数
const onAppStatistic = (index:any) => {
  let obj = {
    type: 'all',
    is_yesterday: false,
    start_day: yesterdayDate(),
    end_day: yesterdayDate(),
    stat: 0
  }
  const params:any = new URLSearchParams();
  params.append('type','all')
  params.append('is_yesterday',false)
  params.append('start_day',yesterdayDate())
  params.append('end_day',yesterdayDate())
  params.append('stat',0)
  getAppStatistic(obj).then((response:any) => {
      const result = response.data.data
      siteList.value[index].yesterday_view_count = result.yesterday.view_count
      onauthorhistory(index)
  }).catch(() => {
    onauthorhistory(index)
  })
}
// 百家号获取总阅读数
const onauthorhistory = (index:any) => {
  getauthorhistory().then((response:any) => {
      const result = response.data.data
      siteList.value[index].total_view_count = formatNumberToWan(result.total.view_count)
      onIncomeoverviewlist(index)
  }).catch(() => {
    onIncomeoverviewlist(index)
  })
}
// 百家号获取总收益
const onIncomeoverviewlist = (index:any) => {
  getNewtotalincome().then((response:any) => {
      const result = response.data.data
      siteList.value[index].income = result
      onGetSquareMissionList(index)
  }).catch(() => {
      onGetSquareMissionList(index)
  })
}
// 获取征文任务列表
const onGetSquareMissionList = (index:any) => {
  let obj = {
    page_no: 1,
    article_type: 1,
    page_size: 18,
    task_attend: 1,
    task_origin: 'market',
    task_type: -1,
    from: 'pc_edit'
  }
  getSquareMissionList(obj).then((response:any) => {
      const result = response.data.data
      siteList.value[index].square_mission_List = result.list
      getArticlePublishNum(index)
  }).catch(() => {
      getArticlePublishNum(index)
  })
}
const formatNumberToWan = (value) => {
  if (value >= 10000) {
    return (value / 10000).toFixed(2) + '万';
  }
  return value;
}
// 百家号获取剩余发布数
const getArticlePublishNum = (index:any) => {
  articlePublishNum({type: 'news'}).then((response:any) => {
      const result = response.data.data
      siteList.value[index].publish_num_left = result.ability.publish_num_left
      siteList.value[index].publish_num_text = result.ability.publish_num_text
      siteList.value[index].activity_list = result.article.activity_list
      onListPulish(index)
  }).catch(() => {
    onListPulish(index)
  })
}
// 文章列表-获取今日发布数
const onListPulish = (idx:any) => {
  let obj = {
        currentPage: 1,
        pageSize: 15,
        search: '',
        type: 'news',
        collection: 'publish',
        clearBeforeFetch: false
    }
    articleLists(obj).then((response:any) => {
      const result = response.data.data
      let arr2 = result.list.filter((item2:any) => isToday(item2.publish_time))
      console.log('今日发布数',arr2)
      siteList.value[idx].today_publish_num = arr2.length
      let arr = result.list.filter((item2:any) => item2['status'] == 'rejected' || (item2['status'] == 'publish' && item2.audit_msg != '') || (item2['status'] == 'forbidden' && item2.audit_msg != ''))
      // 自动删除审核未通过的文章
      if(arr.length > 0) {
          const executeNext2 = (index) => {
            if(index >= arr.length) {
              setTimeout(() => {
                onListPulish(idx)
              }, 2000)
              return
            }
            if(arr[index]['status'] == 'publish') {
              // 状态已发布-先撤回再删除
              articleWithdraw({article_id: arr[index]['article_id']}).then((response:any) => {
                  const result = response.data
                  console.log('articleRemove',result)
                  articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                      console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                      setTimeout(() => {
                        executeNext2(index+1)
                      }, 2000)
                  }).catch(() => {
                    setTimeout(() => {
                      executeNext2(index+1)
                    }, 2000)
                  });
              }).catch(() => {
                setTimeout(() => {
                  executeNext2(index+1)
                }, 2000)
              });
            } else {
              articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                  console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                  setTimeout(() => {
                    executeNext2(index+1)
                  }, 2000)
              }).catch(() => {
                setTimeout(() => {
                  executeNext2(index+1)
                }, 3000)
              });
            }
          }
          executeNext2(0)
      } else {
        onArticleList2(idx)
      }
    }).catch(() => {
      onArticleList2(idx)
    })
}
// 获取文章可发布数
const onArticleList2 = (index:any) => {
  const currentItem = siteList.value[index];
  userSiteArticleList({page: 1,limit: 15, siteId: currentItem.site_id}).then((response:any) => {
    const result = response.data.data
    processItems2(result.data, index)
  }).catch(() => {
    otherGetData(index + 1)
  })
}

// 默认获取是否有下载上传
const processItems2 = async (data:any, index:any) => {
  for (let i in data) {
    let path = `images_${data[i].article_id}`; // 从开始到点号位置截取字符串
    const result = await window.electron.ipcRenderer.invoke('list-directory', path); // 等待操作完成
    // console.log(result)
    // 处理结果或更新数组项
    if(Array.isArray(result.imageArr)) {
      if(result.imageArr.length != 0) {
        data[i]['isDownload'] = true
        data[i]['downloadReason'] = '已解压' // 将修改后的对象添加到新数组中
      } else {
        data[i]['isDownload'] = false
        data[i]['downloadReason'] = ''
      }
    } else {
      data[i]['isDownload'] = false
      data[i]['downloadReason'] = ''
    }

    // 获取图片文件
    let pathJson = `images_${data[i].article_id}.json`;
    const resFile = await window.electron.ipcRenderer.invoke('json-directory', pathJson); // 等待操作完成
    // console.log(resFile,'resFile')
    if(resFile.type == 2) {
      let jsonData = JSON.parse(resFile.urlArr)
      data[i]['isUpload'] = true
      data[i]['uploadReason'] = '已上传' // 将修改后的对象添加到新数组中
      data[i]['uploadText'] = '已上传'
      data[i]['imgNum'] = jsonData.data.length
    } else if(resFile.type == 1 && data[i]['is_release'] == 0 && data[i]['status'] == 50 && data[i]['img_status'] == 20 && data[i]['isDownload']) {
      data[i]['isUpload'] = false
      data[i]['uploadReason'] = '' // 将修改后的对象添加到新数组中
      data[i]['uploadText'] = ''
    } else {
      data[i]['isUpload'] = false
      data[i]['uploadReason'] = '' // 将修改后的对象添加到新数组中
      data[i]['uploadText'] = ''
    }
  }
  let resultData = data.filter((item1:any) =>item1.is_release == 0 && item1.status == 50 && item1.img_status == 20 && item1.isDownload && item1.isUpload)
  if(resultData.length > 0){
      siteList.value[index].pulish_num = resultData.length
  } else {
    siteList.value[index].pulish_num = 0
  }
  otherGetData(index + 1)
};
// 判断是否为今天的时间
const isToday =(date) => { 
  // 获取当前日期
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 将时间设置为今天的 00:00:00
  const specifiedTime = new Date(date);
  specifiedTime.setHours(specifiedTime.getHours() + specifiedTime.getTimezoneOffset() / 60); // 调整时区
  // date.setHours(0, 0, 0, 0); // 将给定日期的时间也设置为00:00:00，以便比较日期部分
  // return date.getTime() === today.getTime();
  return specifiedTime.toDateString() === today.toDateString()
}

/**
 *  每日巡检
 */
const dayInspectionData = () => {
  isStop.value = true
  state.inspectionLoading = true
  otherGetData2(0)
}

// 获取每个账号的数据
const otherGetData2 = (idx:any) => {
  const executeNext_2 = async (index) => {
      if(index >= siteList.value.length) {
        state.inspectionLoading = false
        let monitor = userStore.monitor
        formState.checked1 = monitor
        if(monitor == true && siteList.value.length > 0) {
          isStop.value = false
          onArticleList(0)
        } else {
          if (timer.value) {
            clearTimeout(timer.value)
            timer.value = null
          }
          if (timer2.value) {
            clearTimeout(timer2.value)
            timer2.value = null
          }
          if (timer3.value) {
            clearTimeout(timer3.value)
            timer3.value = null
          }
        }
        return
      }
      const currentItem = siteList.value[index]
      if(currentItem.port_config && currentItem.port_config.cookie) {
        let userInfoObj:any = await GetuserInfo(currentItem.port_config.cookie,currentItem.site_id)
        console.log('设置返回：',userInfoObj)
        let userInfoResult = JSON.parse(userInfoObj)
        if(userInfoResult.success) {
          onListPulish2(index, 1)
        } else {

        }
      }
  }
  executeNext_2(idx)
}
// 文章列表-获取剩余发布数
const onListPulish2 = (idx:any, page:any) => {
  let obj = {
        currentPage: page,
        pageSize: 15,
        search: '',
        type: 'news',
        collection: 'publish',
        clearBeforeFetch: false
    }
    articleLists(obj).then((response:any) => {
      const result = response.data.data
      let arr2 = result.list.filter((item2:any) => isYesterday(item2.publish_time))
      console.log('昨日数据',arr2)
      let arr = arr2.filter((item2:any) => item2['status'] == 'rejected' || (item2['status'] == 'publish' && item2.audit_msg != '') || (item2['status'] == 'forbidden' && item2.audit_msg != '') || item2.rec_amount == 0)
      // 自动删除审核未通过的文章
      if(arr.length > 0) { // task_1600117
          const executeNext2 = (index) => {
            if(index >= arr.length) {
                setTimeout(() => {
                  onListPulish2(idx, 1)
                }, 2000)
              return
            }
            if(arr[index]['status'] == 'publish') {
              // 状态已发布-先撤回再删除
              articleWithdraw({article_id: arr[index]['article_id']}).then((response:any) => {
                  const result = response.data
                  console.log('articleRemove',result)
                  articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                      console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                      setTimeout(() => {
                        executeNext2(index+1)
                      }, 2000)
                  }).catch(() => {
                    setTimeout(() => {
                      executeNext2(index+1)
                    }, 2000)
                  });
              }).catch(() => {
                setTimeout(() => {
                  executeNext2(index+1)
                }, 2000)
              });
            } else {
              articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                  console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                  setTimeout(() => {
                    executeNext2(index+1)
                  }, 2000)
              }).catch(() => {
                setTimeout(() => {
                  executeNext2(index+1)
                }, 3000)
              });
            }
          }
          executeNext2(0)
      } else {
        if(page == 2) {
          otherGetData2(idx + 1)
        } else {
          setTimeout(() => {
            onListPulish2(idx, 2)
          }, 2000)
        }
      }
    }).catch(() => {
      otherGetData2(idx + 1)
    })
}
// 判断是否为昨日的时间
const isYesterday = (date) => { 
  // 获取当前日期
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 将时间设置为今天的 00:00:00
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1); // 设置为昨天的日期
  yesterday.setHours(0, 0, 0, 0); // 将时间重置为昨天的午夜
  const specifiedTime = new Date(date);
  specifiedTime.setHours(specifiedTime.getHours() + specifiedTime.getTimezoneOffset() / 60); // 调整时区
  // date.setHours(0, 0, 0, 0); // 将给定日期的时间也设置为00:00:00，以便比较日期部分
  // return date.getTime() === today.getTime();
  console.log('时间判断：',specifiedTime.toDateString(),yesterday.toDateString(), specifiedTime.toDateString() === yesterday.toDateString())
  return specifiedTime.toDateString() === yesterday.toDateString()
}
// 全选
const onCheckAllChange = (e: any) => {
  let resultData = siteList.value.filter((item1:any) =>item1.pulish_num > 0)
  Object.assign(state, {
    selectedRows: e.target.checked ? resultData : [],
    indeterminate: false,
  });
};
// 监听选中的数据
watch(
  () => state.selectedRows,
  val => {
    let resultData = siteList.value.filter((item1:any) =>item1.pulish_num > 0) // 获取发布数大于0可以选择
    state.indeterminate = !!val.length && val.length < resultData.length;
    state.checkAll = val.length === resultData.length;
  },
);
// 选中事件
const oncheckbox = (data:any) => {
   console.log(data)
}
// 单个选中事件
const onCheckboxClick = (item) => {
  console.log('Checkbox clicked:', item);
};

const menuItems = ref([
  { text: '编辑', action: () => alert('编辑功能') },
]);
const position = ref({ x: 0, y: 0 });
const showContextMenu = (event, site_id) => {
  event.preventDefault();
  siteList.value.forEach((item:any) => {
    if(site_id == item.site_id) {
      item.isVisible = true
    } else {
      item.isVisible = false
    }
  })
  const contextMenuWrapper = event.currentTarget as HTMLElement;
  const rect = contextMenuWrapper.getBoundingClientRect();
  position.value = { x: event.clientX - rect.left, y: event.clientY - rect.top };
  // 在这里调用 ContextMenu 的 showMenu 方法
};

const hideContextMenu = (data:any) => {
  siteList.value.forEach((item:any) => {
    if(data.site_id == item.site_id) {
      item.isVisible = false
    }
  })
  // 在这里调用 ContextMenu 的 hideMenu 方法
};
const hideModel = () => {
  isStop.value = true
  onUserSiteList()
}
const isDownloadResume = ref(false)
onMounted(() => {
  isDownloadResume.value = false
  onUserSiteList()
  //在负责渲染的vue文件created生命周期函数中接受消息，做相应处理
  window.electron.ipcRenderer.removeAllListeners('updateProgressing2');
  window.electron.ipcRenderer.on('updateProgressing2', (_, value) => {
    console.log(idxs.value,'idxs.value')
    if(siteList.value.length > 0 && idxs.value >= 0) {
      siteList.value[idxs.value].progressBar = value.flag == 1  ?  value.process : ''
      if(value.type == 'completed' && value.process == '100%' && !isDownloadResume.value) {
        isDownloadResume.value = true
        siteList.value[idxs.value].download_status = true
        siteList.value[idxs.value].download_status_reason = `已解压`
      }
    }
  });
})
watchEffect(() => {

})
//离开界面
onBeforeUnmount(() => {
    // 每次离开当前界面时，清除定时器
    console.log('33243onBeforeUnmount')
    clearTimeout(timer.value)
    timer.value = null
    clearTimeout(timer2.value)
    timer2.value = null
    isStop.value = true
    clearTimeout(timer3.value)
    timer3.value = null
})

// 退出登录
const onLogout = () => {
  userStore.removeLogout().then(() => {

  })
  sessionStorage.remove(`site_list_num`)
  isStop.value = true
  router.push('/login')
}
</script>

<template>
  <div class="home">
    <div class="home-top">
      <a-breadcrumb>
        <a-breadcrumb-item>首页</a-breadcrumb-item>
      </a-breadcrumb>
      <div style="display: flex;align-items: center;">
        <a-form
          style="margin-top: 0px"
          ref="formStateRef"
          layout="inline"
          :model="formState"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          >
          <a-form-item label="实时监测" name="region">
            <a-switch v-model:checked="formState.checked1" checked-children="开" un-checked-children="关" @change="onChangeMonitor" />
          </a-form-item>
        </a-form>
        <a class="logout" @click="onLogout" style="color:black">退出</a>
      </div>
    </div>
    <div v-if="inProgressData">
      <a-alert message="" type="info" banner :show-icon="false" closable>
        <template #description>
            <p style="margin-bottom: 0;">
              {{ inProgressData.name }}
              <a-tag style="margin-left:20px" v-if="inProgressData.download_status" color="success">{{inProgressData.download_status_reason}}</a-tag>
              <!-- {{ inProgressData.imgNum ? (inProgressData.imgNum) : '' }}{{ inProgressData.imgNum ? (inProgressData.imgNum) : '' }}-->
              <a-tag v-else-if="!inProgressData.download_status && inProgressData.download_status_reason" :color="inProgressData.errorColor2 ? inProgressData.errorColor2 : 'orange'">{{inProgressData.download_status_reason}} {{  inProgressData.progressBar && inProgressData.download_status_reason == '正在解压' ? (inProgressData.progressBar) : '' }}</a-tag>
              <a-tag v-if="inProgressData.upload_status" color="blue">{{inProgressData.upload_text}}</a-tag>
              <span v-else-if="!inProgressData.isUpload && inProgressData.upload_status_reason">
                <a-tooltip>
                  <template #title>
                    <span>{{inProgressData.upload_status_reason}}</span>
                  </template>
                  <a-tag style="cursor: pointer;" :color="inProgressData.errorColor1 ? inProgressData.errorColor1 : 'gold'">{{inProgressData.upload_text}}</a-tag>
                </a-tooltip>
              </span>
              <a-tag v-if="inProgressData.list_status" color="default">已完成</a-tag>
              <span v-else-if="!inProgressData.list_status && inProgressData.list_status_reason">
                <a-tooltip>
                  <template #title>
                    <span>{{inProgressData.list_status_reason}}</span>
                  </template>
                  <a-tag style="cursor: pointer;" :color="inProgressData.errorColor ? inProgressData.errorColor : 'gold'">{{inProgressData.list_status_text}}</a-tag>
                </a-tooltip>
              </span>
            </p>
      </template>
      </a-alert>
    </div>
    <!-- <a-form
      style="justify-content: end;margin-top:10px;"
      ref="formRef"
      layout="inline"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      >
      <a-form-item label="">
         <a-button  style="color: #4096ff" @click="onDataRefresh">数据刷新<RedoOutlined /></a-button>
      </a-form-item>
      <a-form-item label="">
        <div style="margin-bottom: 16px;text-align: right;">
          <a-button type="primary" :disabled="!hasSelected" :loading="state.loading" @click="onPulish">
            {{ title }}
          </a-button>
        </div>
      </a-form-item>
    </a-form> -->
    <div style="display: flex;align-items: center;justify-content: space-between;">
      <a-checkbox
        v-model:checked="state.checkAll"
        :indeterminate="state.indeterminate"
        @change="onCheckAllChange"
      >
        全选
      </a-checkbox>
      <publishArticle :selectedRows="state.selectedRows" :refreshLoading="state.refreshLoading" :inspectionLoading="state.inspectionLoading" @refresh-data="onDataRefresh" @stop-upload="onPulish" @clear-select-data="onClear" @refresh-list="onRefreshList" @day-inspection-data="dayInspectionData"></publishArticle>
    </div>
    <div>
      <a-spin :spinning="initLoading" wrapperClassName="listCard">
        <div v-if="siteList.length > 0" class="list-s">
          <a-checkbox-group v-model:value="state.selectedRows" @change="oncheckbox" style="width: 100%">
            <a-card :bodyStyle="{  padding: '24px 0' }" class="platform" @contextmenu.prevent="showContextMenu($event, item.site_id)" v-for="(item) in siteList" :key="item.site_id"  @click="onDetails(item.site_id, item.port_config.cookie)">
                <div class="container-site">
                  <a-checkbox :value="item" :disabled="item.pulish_num > 0 ? false : true" class="checkboxs" @click.stop="onCheckboxClick(item)"></a-checkbox>
                  <div class="site-name">{{item.name}}</div>
                  <div style="display: flex;flex-wrap: wrap;">
                    <div class="right-content-module">
                      <div>前日阅读</div>
                      <div>{{ item.read_amount && item.read_amount.length > 0 ? item.read_amount[0].total_pv : '0' }}</div>
                    </div>
                    <!-- <div class="right-content-module">
                      <div>昨日阅读</div> -->
                      <!-- {{ item.read_amount && item.read_amount.length > 0 ? item.read_amount[1].total_pv : '0' }} -->
                      <!-- <div>{{ item.yesterday_view_count ? item.yesterday_view_count : '0' }}</div>
                    </div> -->
                    <div class="right-content-module">
                      <div>总阅读量</div>
                      <div>{{ item.total_view_count ? item.total_view_count : '0' }}</div>
                    </div>
                    <div class="right-content-module">
                      <div>昨日收益</div>
                      <div>{{ item.income && item.income.yesterday_income ? formatNumberToWan(item.income.yesterday_income) : '0' }}</div>
                    </div>
                    <!-- <div class="right-content-module">
                      <div>本周收益</div>
                      <div>{{ item.incomeInfo && item.incomeInfo.week && item.incomeInfo.week.current ? item.incomeInfo.week.current : '0'}}</div>
                    </div> -->
                    <div class="right-content-module">
                      <div>总收益</div>
                      <div>{{ item.income && item.income.total_income ? formatNumberToWan(item.income.total_income) : '0' }}</div>
                    </div>
                    <div class="right-content-module">
                      <div>今日发布</div>
                      <div style="color: #52c41a">{{ item.today_publish_num ?item.today_publish_num : '待统计'}}</div>
                    </div>
                    <div class="right-content-module">
                      <div>剩余发布</div>
                      <div style="color: #52c41a">
                        <a-tooltip :title="item.publish_num_text">
                            <div>
                              {{ item.publish_num_left || 0 }}
                            </div>
                        </a-tooltip>
                      </div>
                    </div>
                    <div class="right-content-module">
                      <div>文章发布时间</div>
                      <div style="color: #52c41a">{{item.prev_time || '-'}}</div>
                    </div>
                    <div class="right-content-module">
                      <div>文章可发布数</div>
                      <div style="color: #52c41a"> {{ item.pulish_num || 0 }}</div>
                    </div>
                    {{ item.publishReason }}
                    <div class="right-content-module" v-if="item.publishText">
                      <a-tag v-if="item.isPublish" color="default">{{item.publishText}}</a-tag>
                      <span v-else-if="!item.isPublish && item.publishReason">
                        <a-tooltip>
                          <template #title>
                            <span>{{item.publishReason}}</span>
                          </template>
                          <a-tag style="cursor: pointer;" :color="item.errorColor3 ? item.errorColor3 : 'gold'">{{item.publishText}}</a-tag>
                        </a-tooltip>
                      </span>
                    </div>
                  </div>
                </div>
                <!-- <div>
                  <a-tag v-if="item.download_status" color="success">{{item.download_status_reason}}</a-tag>
                  <a-tag v-else-if="!item.download_status && item.download_status_reason" color="orange">{{item.download_status_reason}}</a-tag>
                  <a-tag v-if=" item.upload_status" color="blue">完成上传</a-tag>
                  <a-tag v-else-if="!item.isUpload && item.upload_status_reason" color="gold">{{item.upload_status_reason}}</a-tag>
                  <a-tag v-if=" item.list_status" color="default">完成执行</a-tag>
                  <a-tag v-else-if="!item.isUpload && item.list_status_reason" color="gold">{{item.list_status_reason}}</a-tag>
                </div> -->
                <ContextMenu
                  :menuItems="menuItems"
                  :isVisible="item.isVisible"
                  :position="position"
                  :site_id="item.site_id"
                  :name="item.name"
                  @hide-menu="hideContextMenu"
                  @hide-model="hideModel"
                />
            </a-card>
          </a-checkbox-group>
        </div>
        <div style="width: 100%;" v-else>
          <a-empty :image="simpleImage" />
        </div>
      </a-spin>
    </div>
    <div class="pagination">
      <a-pagination  v-model:current="current" v-model:pageSize="pageSize" :total="total" show-less-items @change="onChange" />
    </div>
  </div>
</template>

<style scoped>
.list-s{
    /* display: grid;
    grid-template-columns: 150px 150px 150px 150px 150px;
    grid-column-gap: 20px; */
    display: flex;
    align-items: center;
    align-items: center;
    flex-wrap: wrap;
    padding-top:20px;
    /* margin-left: -5px; */
}
.platform{
  margin-bottom: 20px;
  cursor: pointer;
  /* text-align: center; */
  position: relative;
  /* width: 228px; */
  width:100%;
  /* margin-right: 6px;
  margin-left: 3px; */
  background-color: #2565ad;
  color: #fff;
}
.checkboxs{
  padding: 0 15px;
}
.home-top{
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.logout{
  font-size: 14px;
  cursor: pointer;
}
.pagination{
  margin-top: 20px;
  text-align: right;
}
.container-site{
   display: flex;
   align-items: center;
}
.site-name{
   /* border-right: 1px solid #f0f0f0; */
   /* padding-right: 30px; */
   width: 200px;
}
.right-content-module{
  margin-left: 25px;
  padding-right: 30px;
  margin-top: 8px;
  /* text-align: center; */
}
.right-content-module div:nth-child(2) {
  text-align: center;
}
.listCard{
  width:100%;
}
</style>
